export default function transformer(file, api) {
  const j = api.jscodeshift;
  const root = j(file.source);

  // 检查是否有 connect 调用 或 @connect 装饰器
  const hasConnectCall = root.find(j.CallExpression, {
    callee: { name: 'connect' },
  }).length > 0;

  const hasConnectDecorator = root.find(j.Decorator, {
    expression: { callee: { name: 'connect' } }
  }).length > 0;

  if (!hasConnectCall && !hasConnectDecorator) {
    return; // 没有 connect 相关内容直接跳过
  }

  // 检测是否已经包了 withRouter
  const hasWithRouterCall = root.find(j.CallExpression, {
    callee: { name: 'withRouter' },
  }).length > 0;

  const hasWithRouterDecorator = root.find(j.Decorator, {
    expression: { callee: { name: 'withRouter' } }
  }).length > 0;

  if (!hasWithRouterCall && !hasWithRouterDecorator) {
    // 添加 import 语句（如果还没引入）
    const hasImportWithRouter = root.find(j.ImportDeclaration, {
      source: { value: '@/utils/withRouter' }
    }).length > 0;

    if (!hasImportWithRouter) {
      const lastImport = root.find(j.ImportDeclaration).at(-1);
      lastImport.insertAfter(
        j.importDeclaration(
          [j.importSpecifier(j.identifier('withRouter'))],
          j.literal('@/utils/withRouter')
        )
      );
    }

    if (hasConnectCall) {
      // connect(...) 包裹的情况
      root.find(j.ExportDefaultDeclaration).forEach(path => {
        path.node.declaration = j.callExpression(
          j.identifier('withRouter'),
          [path.node.declaration]
        );
      });
    } else if (hasConnectDecorator) {
      // @connect 装饰器的情况，追加 @withRouter
      root.find(j.ClassDeclaration).forEach(path => {
        path.node.decorators = path.node.decorators || [];
        path.node.decorators.push(
          j.decorator(j.identifier('withRouter'))
        );
      });
    }
  }

  return root.toSource({ quote: 'single' });
}
